<template>
  <div class="putstore">
        <div class="top-add">
            <div style="width:80%">
              <el-page-header @back="backOutStore" content="新增出库单"></el-page-header>
            </div>
            <div>
                 <el-button style="width:80px" size="mini" type="primary" @click="selectProd">选择装备</el-button>
                <el-button style="width:80px" size="mini" type="primary" @click="submitOutstore">保存</el-button>
                <!-- <el-button style="width:80px" size="mini" type="primary" @click="backOutStore">取消</el-button> -->
            </div>
            
            
        </div>
      <el-row :gutter="16" style="line-height:40px;margin-top:-20px;margin-bottom:20px">
        <el-col :span="4">
          <div class="">
            <label for="">出库单号</label>
            <el-input v-model="orderNum" disabled size="small" placeholder="自动生成" style="width:80%"></el-input>
          </div>
        </el-col>

         <el-col :span="4">
          <div>
            <label for="">出库类型</label>
            <div class="main-content">
              <el-select v-model="outType" placeholder="请选择" style="width:80%"  size="small">
                <el-option
                  v-for="item in outTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div class="">
            <label for="">出库日期</label>
            <el-date-picker size="small" type="date" style="width:80%" placeholder="选择日期" v-model="outDate"></el-date-picker>
          </div> 
        </el-col>

        <el-col :span="4">
          <div class="">
            <label for="">制单人</label>
            <el-input v-model="outPerson" size="small" style="width:80%"></el-input>
          </div> 
        </el-col>

        <el-col :span="4">
            <label for="">备注</label>
            <el-input v-model="outRemark" size="small" placeholder="" style="width:90%"></el-input>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table :data="outSelectProd" border style="width: 100%">
            <el-table-column label="图片" width="60">
              <template slot-scope="scope">
                <div>
                  <img style="width:40px;height:40px;" :src="scope.row.prodImg" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="categoryTwoName" label="装备细类"></el-table-column>
            <el-table-column prop="prodCode" label="装备编号" width="120"></el-table-column>
            <el-table-column prop="prodName" label="装备名称" width="120"></el-table-column>
            <el-table-column prop="prodSpecial" label="规格" width="80"></el-table-column>
            <el-table-column prop="prodResiduenum" label="可出库数"></el-table-column>
            <el-table-column prop="prodNum" label="出库数">
              <template slot-scope="scope">
                <div>
                  <el-input onkeyup="value=value.replace(/[^\d]/g,'')" size="mini" 
                    v-model="scope.row.prodNum" required @input="changeNums($event,scope.row)"
                    @change="changeEdit($event,scope.row)"
                    placeholder="请输入数字"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="emit" label="单位"></el-table-column>
            <!-- <el-table-column prop="prodPrice" label="价格"></el-table-column> -->
            <el-table-column prop="areaName" label="库区"></el-table-column>
            <el-table-column prop="departmentCode" label="库位"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-delete" @click="delSelectProd(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      

      <div class="autospace"></div>

      <selectstock :selectprodDialog.sync="selectprodDialog"></selectstock>
  </div>
</template>

<script>
import { OutStore, FindOutOrderById, UpdateOutOrder } from '@/api/outstore';
import selectstock from '@/components/selectStock';
import { getStore } from '@/utils/app.js'
export default {
  name: 'putstore',
  components: {
    selectstock
  },
  data() {
    return {
        selectprodDialog: false, // 打开选择商品弹框
        is_search: false,
        orderNum: '',
        outType: '',
        outDate: new Date(),
        outPerson: '',
        outRemark: '',
        newSelect: [],
        outId: null,
        outSelectProd: [
           
        ],
        editOutProd: [],
        outTypeList: [
            {id: 1, name:'日常出库'},
					  {id: 2, name:'借用出库'},
					  {id: 3, name:'其他出库'},
        ]
    }
    
  },
  computed: {
    storeid() {
      return this.$store.state.store.store_id || getStore();
    },
    main_store() {
      return this.$store.state.store.main_store;
    },
    getSelectprod() {
      return this.$store.state.ware.selectProds;
    }
  },
   watch: {
    selectprodDialog(newVal) {
      if (!newVal) {
        // if (this.outId) {
        //   // 修改时将新增的加上type类型add
        //   let updateSelect = this.getSelectprod;
        //   if (updateSelect.length != 0) {
        //     let  updateTwo = []
        //     updateSelect.forEach( e => {
        //       let currentTwo = {
        //         deliveryId: e.deliveryId,
        //         outId:  this.outId,
        //         prodNum: e.prodNum,
        //         stockId: e.stockId,
        //         type: 'add'
        //       }
        //       updateTwo.push(currentTwo)
        //     })
        //     updateTwo = JSON.parse(JSON.stringify(updateTwo));
        //     this.editOutProd = this.editOutProd.concat(updateTwo) 
        //   }
        // }
        if (this.getSelectprod.length != 0) {
          this.getSelectprod.forEach(e => e.type = 'add')
        }
        let newArr = this.outSelectProd.concat(this.getSelectprod);
        this.newSelect = JSON.parse(JSON.stringify(newArr));
        for( let n = 0; n < this.newSelect.length; n++) {        
          this.newSelect[n].edit_id = n + 1;
        }
        // this.outSelectProd = this.newSelect
        // 去除里面重复的商品
        this.outSelectProd = this.newSelect.filter((item, index, origin) => 
          index === origin.findIndex(itemInner => {
            return itemInner.stockId === item.stockId
          }
        ))
        // console.log(this.outSelectProd)
      }
    }
  },
  methods:{
    // 输入出库数时进行判断
    changeNums(value,item) {
      let newStock = parseInt(item.prodResiduenum);
      let newVal = parseInt(value);
      let ifTrue = newStock - newVal;
      if (ifTrue < 0) {
        this.$message({
          message: '库存数不足,请重新输入',
          type: 'warning'
        })
        item.prodNum = ""
      }
      if (item.type == 'add') {
        return
      } else {
        item.type = 'edit'
      }
    
    },
    changeEdit(value,item) {
      
     
    },
    // 去选择商品
    selectProd() {
      this.selectprodDialog = true;
    },
    backOutStore() {
        this.$router.push('/outstore')
    },
    delSelectProd(el) {
      if (this.outId) {
        if (el.type == 'add') {
          this.outSelectProd = this.outSelectProd.filter( e => e.stockId != el.stockId);  
        } else {
          let currentDelete = this.outSelectProd.filter( e => e.stockId == el.stockId);
          let currentTwo = {
            deliveryId: currentDelete[0].deliveryId,
            outId:  this.outId,
            prodNum: currentDelete[0].prodNum,
            stockId: currentDelete[0].stockId,
            type: 'delete'
          }
          this.editOutProd.push(currentTwo)

          this.outSelectProd = this.outSelectProd.filter( e => e.stockId != el.stockId);  
        }
      } else {
        this.outSelectProd = this.outSelectProd.filter( e => e.stockId != el.stockId);  
      }
    },
    // 保存出库信息
    submitOutstore() {
      if (!this.outType) {
        this.$message({
          message: '请选择出库类型',
          type: 'warning'
        })
      } else {
        if (this.outSelectProd.length == 0) {
          this.$message({
            message: '请选择出库装备',
            type: 'warning'
          })
        } else {
          this.outDate = this.formatDate(this.outDate);
          let arrOut = this.outSelectProd.filter( el => {    // 未输入出库数的装备
            if (!el.prodNum) {
              return el
            }
          })
      
          let editout = this.outSelectProd.filter( el => {    // 过滤修改后的装备
            if (el.type == 'edit') {
              return el
            }
          })
          let addout = this.outSelectProd.filter( el => {    // 过滤新增的装备
            if (el.type == 'add') {
              return el
            }
          })
          let editoutTwo = []
          editout.forEach(el => {
            let currentTwo = {
              deliveryId: el.deliveryId,
              outId:  this.outId,
              prodNum: el.prodNum,
              stockId: el.stockId,
              type: 'edit'
            }
            editoutTwo.push(currentTwo)
          })
          // 对新增装备重置类型
          addout.forEach(el => {
            let addTow = {
              deliveryId: el.deliveryId,
              outId:  this.outId,
              prodNum: el.prodNum,
              stockId: el.stockId,
              type: el.type
            }
            this.editOutProd.push(addTow)
          })
          this.editOutProd = this.editOutProd.concat(editoutTwo)
          if (arrOut.length != 0) {
            this.$message({
              message: '请输入出库数',
              type: 'warning'
            })
          } else {
              if (this.outId) {
                // 存在即修改
                let reqData = {
                    outId: this.outId,
                    dorderNum: this.orderNum,
                    outTypeid: this.outType,
                    outDate: this.outDate,
                    outPerson: this.outPerson,
                    outRemark: this.outRemark,
                    list: this.editOutProd,
                }
               console.log(this.editOutProd)
                UpdateOutOrder(reqData).then( res => {
                  this.$message({
                    message: res.data.msg,
                    type: 'success'
                  })
                  setTimeout(() => {
                    this.$router.push('/outstore')
                  }, 1000)
                }).catch( error => console.log(error))

              } else {
                // 不存在即新增
                  let reqData = {
                      dorderNum: this.orderNum,
                      outTypeid: this.outType,
                      outDate: this.outDate,
                      outPerson: this.outPerson,
                      outRemark: this.outRemark,
                      outProds: this.outSelectProd,
                  }
                  // console.log(reqData)
                  OutStore(reqData).then( res => {
                    this.$message({
                      message: res.data.msg,
                      type: 'success'
                    })
                    setTimeout(() => {
                      this.$router.push('/outstore')
                    }, 1000)
                  }).catch( error => console.log(error))
              }
          }
        }
      }
      
    }
  },

  mounted() {
    this.outId = this.$route.query.outId;
    if (this.outId) {
      FindOutOrderById(this.outId).then( res => {
        let orderDetail = res.data[0];
        orderDetail.outDate = this.formatDate(orderDetail.outDate);
        this.orderNum = orderDetail.dorderNum;
        this.outDate = orderDetail.outDate;
        this.outPerson = orderDetail.outPerson;
        this.outRemark = orderDetail.outRemark;
        this.outType = orderDetail.outTypeid;
        if (orderDetail.outProds && orderDetail.outProds.length != 0) {
          this.outSelectProd = orderDetail.outProds;
          // for( let n = 0; n < this.outSelectProd.length; n++) {        
          //   this.outSelectProd[n].edit_id = n + 1;
          // }
        }  
      })
    }   
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/config.scss';

  .label-wrap {
    &.category { @include labelwrap(left,100,40); }
    &.date {
      @include labelwrap(center,50,40); }
    &.keyword { @include labelwrap(right,110,40); }
  }
  .autospace {
    height: 30px;
  }
  
  .top-add {
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    // font-weight: 700;
    border-bottom: 1px solid #f1f1f1;
    display: flex;
  }
</style>
  
